package eu.connect.im;

import java.io.UnsupportedEncodingException;
import java.util.Scanner;

import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.entity.StringEntity;

import com.echomine.common.ParseException;
import com.echomine.jabber.JID;
import com.echomine.jabber.JabberChatMessage;
import com.echomine.jabber.JabberPresenceMessage;
import com.echomine.jabber.msg.RosterIQMessage;
import com.echomine.jabber.msg.RosterItem;


public class IMCONNECTor
{
    public Partner xmppClient;
    public Partner xmppServer;
    public MessageQueue queue;
    
    
    public static void main(String[] args) throws Exception
    {
    	IMCONNECTor connector = new IMCONNECTor();
    	connector.queue = new MessageQueue();
    	connector.queue.start();
    	connector.xmppClient = null;
    	connector.xmppServer = null;
    	
        Thread t = new RequestListenerThread(connector, 9999);
        t.setDaemon(false);
        t.start();
  
        connector.run();
        
        Scanner s= new Scanner(System.in);
        s.next();
        
        connector.queue.shutdown();
        
        Thread.sleep(1000);
        
    }
    
    public void run()
    {
    	int omsChatState = 0;
    	String omsMessage = null;
    	
    	while (queue.isRunning())
    	{
    		Message msg = queue.waitForMessage();

    	/*	if (msg.getMessageType().equals("HttpRequest"))
    			msg.getYourrole().sendMessage(msg);
    		else if (msg.getMessageType().equals("HttpResponse"))
    			msg.getYourrole().sendMessage(msg);
    		else if (msg.getMessageType().equals("JabberMessage") && msg.getSource().equals("client"))
    			this.xmppServer.sendMessage(msg);
    		else if (msg.getMessageType().equals("JabberMessage") && msg.getSource().equals("server"))
    			this.xmppClient.sendMessage(msg);*/
    		
    		
    		if (msg.getMessageType().equals("HttpRequest"))
    		{
    			HttpRequest request = (HttpRequest)msg.getMessageEntity();
    			
    			if (request instanceof HttpEntityEnclosingRequest)
    			{
    				HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest)request;
    				
    				String entity = Utils.decodeHttpEntity(entityRequest.getEntity());
    				
    				if (entity.indexOf("#messagecenter#") != -1)
    				{
    					String to = Utils.getOMSFieldValue(entity, "to");
    					
    					if (to.equals("CONNECTor"))
    					{
    						String content = Utils.getOMSFieldValue(entity, "message");
    						JabberChatMessage chatMsg = new JabberChatMessage("chat");
        					try {
    							chatMsg.setTo(new JID("mmsxzy@ubuntu-jabber.net"));
    							chatMsg.setFrom(new JID("connector@pku.edu.cn"));
    						} catch (ParseException e) {
    							// TODO Auto-generated catch block
    							e.printStackTrace();
    						}
        					chatMsg.setBody(content);
        					Message newMsg = new Message(chatMsg, "JabberMessage", "server");
        					this.queue.addMessage(newMsg);
        					continue;
    					}
    					
    				}
    				else if(entity.indexOf("#messagecenter:Body><OMS_ReceiveMessage>") != -1 && omsChatState == 2)
    				{
    					HttpResponse response = Utils.getAResponceMessage(request.getRequestLine().getProtocolVersion());
    					String message = "<?xml version='1.0' encoding='UTF-8'?>#messagecenter:Body><OMS_ReceiveMessage><Message><Sender>CONNECTor</Sender>"
    						+ "<DateSent>" + Utils.getDateTime() + "</DateSent><Content>" + omsMessage + "</Content></Message></OMS_ReceiveMessage></#messagecenter:Body>";
    					try {
							response.setEntity(new StringEntity(message,"UTF-8"));
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
    					Message newMsg = new Message(response, "HttpResponse", "server");
    					msg.getMyrole().sendMessage(newMsg);
    					
    					omsChatState = 0;
    					omsMessage = null;
    					
    					continue;
    				}
    				
    				try {
    					entityRequest.setEntity(new StringEntity(entity, "UTF-8"));
    				} catch (UnsupportedEncodingException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    			
    			msg.getYourrole().sendMessage(msg);
    		}
    		else if (msg.getMessageType().equals("HttpResponse"))
    		{
    			HttpResponse response = (HttpResponse)msg.getMessageEntity();

				String entity = Utils.decodeHttpEntity(response.getEntity());
				    				
				if (entity.indexOf("#userlist:Body>") != -1)
				{
					String fakeFriend1 = "<OnlineUser><UserName>CONNECTor</UserName><DisplayName>CONNECTor</DisplayName><Status>online</Status></OnlineUser>";
					String fakeFriend2 = "<OnlineUsers><OnlineUser><UserName>CONNECTor</UserName><DisplayName>CONNECTor</DisplayName><Status>online</Status></OnlineUser></OnlineUsers>";
					int userListPos = entity.indexOf("</OnlineUsers>");
					if (userListPos != -1)
					{
						String s1 = entity.substring(0, userListPos);
		        		String s2 = entity.substring(userListPos, entity.length());
		        		entity = s1 + fakeFriend1 + s2;
					}
					else
					{
						userListPos = entity.indexOf("</Userlist>");
						String s1 = entity.substring(0, userListPos - 1);
		        		String s2 = entity.substring(userListPos, entity.length());
		        		entity = s1 + fakeFriend2 + s2;
					}
    			}
				else if (entity.indexOf("#messagecenter:Body><OMS2_GetNewMessageStatus>") != -1)
				{
					String newMessageStatus = Utils.getOMSFieldValue(entity, "NewMessage");
					if (newMessageStatus.equals("false") && omsChatState == 1)
					{
						entity = Utils.modifyOMSFieldValue(entity, "NewMessage", "true");
						omsChatState = 2;
					}
					
				}
				
				try {
					response.setEntity(new StringEntity(entity, "UTF-8"));
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
								
    			msg.getYourrole().sendMessage(msg);
    			
    		}
    		else if (msg.getMessageType().equals("JabberMessage") && msg.getSource().equals("client"))
    		{
    			if (msg.getMessageEntity() instanceof JabberChatMessage)
    			{
    				JabberChatMessage chartMsg = (JabberChatMessage)msg.getMessageEntity();
    				if (chartMsg.getTo().getJIDWithoutResource().equals("connector@pku.edu.cn"))
    				{
    					if (omsChatState != 0)
    						this.queue.addMessage(msg);
    					else
    					{
    						omsChatState = 1;
    						omsMessage = chartMsg.getBody();
    					}
    					continue;
    				}
    			}
    			
    			this.xmppServer.sendMessage(msg);
    		}
    		else if (msg.getMessageType().equals("JabberMessage") && msg.getSource().equals("server"))
    		{
    			if (msg.getMessageEntity() instanceof RosterIQMessage)
    			{
    				RosterIQMessage rosterIQmsg = (RosterIQMessage)msg.getMessageEntity();
					RosterItem item = null;
					try {
						item = new RosterItem(new JID("CONNECTor@pku.edu.cn"),"CONNECTor");
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					item.setSubscription(RosterItem.SUBSCRIBE_BOTH);
					rosterIQmsg.addRosterItem(item);
					this.xmppClient.sendMessage(msg);
					JabberPresenceMessage presenceMsg = new JabberPresenceMessage("available");
					presenceMsg.setStatus("Online");
					try {
						presenceMsg.setFrom(new JID("CONNECTor@pku.edu.cn"));
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					Message presence = new Message(presenceMsg, "JabbeMessage", "server");
					this.xmppClient.sendMessage(presence);
					continue;
    			}
    			
    			this.xmppClient.sendMessage(msg);
    		}
    			
    	}
    }
}
